﻿/*
 * MessageContext
 * 
 * Save necessary information when message is being processed
 * 
 * Author: snowdreamist
 * Date: 2011/11/24
 * 
 */

using System;
using System.Collections.Generic;
using System.Net;
using System.Linq;
using System.Text;
using BitTorrentSharp.KRPC.Contract;

namespace BitTorrentSharp.KRPC.Messages
{
    public class MessageContext : IDisposable
    {

        #region threadstatic
        /// <summary>
        /// ThreadStatic current message context
        /// </summary>
        [ThreadStatic]
        private static MessageContext _current;
        /// <summary>
        /// Current message context [ThreadStatic]
        /// </summary>
        public static MessageContext Current
        {
            get
            {
                return _current;
            }
            private set
            {
                _current = value;
            }
        }

        #endregion

        internal MessageContext()
        {
            if (MessageContext.Current != null)
                throw new InvalidOperationException("MessageContext.Current is not null");
            MessageContext.Current = this;
        }

        #region basic information
        /// <summary>
        /// Host
        /// </summary>
        public KRPCHost Host { get; set; }
        /// <summary>
        /// Remote endpoint
        /// </summary>
        public IPEndPoint EndPoint { get; set; }
        /// <summary>
        /// Target service
        /// </summary>
        public KRPCService Service { get; set; }
        /// <summary>
        /// Target operation
        /// </summary>
        public KRPCOperation Operation { get; set; }
        /// <summary>
        /// Message
        /// </summary>
        public Message Message { get; set; }
        /// <summary>
        /// If current message is a response
        /// </summary>
        public bool IsResponse { get; set; }

        #endregion

        #region invoke and result
        /// <summary>
        /// Parameters
        /// </summary>
        public List<KRPCParameter> Parameters { get; set; }
        /// <summary>
        /// If error occurred when invoke target method
        /// </summary>
        public Exception Error { get; set; }
        /// <summary>
        /// Result
        /// </summary>
        public List<KRPCReturnValue> Results { get; set; }

        #endregion

        public void Dispose()
        {
            MessageContext.Current = null;
        }
    }
}
